<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form label-position="right" :model="salaryForm" :label-width="formLabelWidth" ref="salaryFormRef" :rules="rules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="员工姓名" prop="employeeName">
              <el-input v-model="salaryForm.employeeName" placeholder="请选择员工姓名" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findEmployee"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="基本工资" prop="basicSalary">
              <el-input-number v-model="salaryForm.basicSalary" :precision="2" :step="0.1" :min="1" :max="99999999"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="绩效工资" prop="performanceSalary">
              <el-input-number v-model="salaryForm.performanceSalary" :precision="2" :step="0.1" :min="1" :max="99999999"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="奖金" prop="bonus">
              <el-input-number v-model="salaryForm.bonus" :precision="2" :step="0.1" :min="1" :max="99999999"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="津贴" prop="allowance">
              <el-input-number v-model="salaryForm.allowance" :precision="2" :step="0.1" :min="1" :max="99999999"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="加班费" prop="overtimePay">
              <el-input-number v-model="salaryForm.overtimePay" :precision="2" :step="0.1" :min="1" :max="99999999"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="社保扣除" prop="socialSecurityDeduction">
              <el-input-number v-model="salaryForm.socialSecurityDeduction" :precision="2" :step="0.1" :min="1" :max="99999999"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="公积金扣除" prop="housingFundDeduction">
              <el-input-number v-model="salaryForm.housingFundDeduction" :precision="2" :step="0.1" :min="1" :max="99999999"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="个人所得税扣除" prop="personalIncomeTaxDeduction">
              <el-input-number v-model="salaryForm.personalIncomeTaxDeduction" :precision="2" :step="0.1" :min="1" :max="99999999"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="其他扣除" prop="otherDeductions">
              <el-input-number v-model="salaryForm.otherDeductions" :precision="2" :step="0.1" :min="1" :max="99999999"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="应发工资" prop="grossSalary">
              <el-input-number v-model="salaryForm.grossSalary" :precision="2" :step="0.1" :min="1" :max="99999999"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="实发工资" prop="netSalary">
              <el-input-number v-model="salaryForm.netSalary" :precision="2" :step="0.1" :min="1" :max="99999999"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="发放日期" prop="payDate">
              <el-date-picker
                  v-model="salaryForm.payDate" type="date" placeholder="发放日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="salaryForm.paymentMethod" placeholder="请选择支付方式">
                <el-option label="银行转账" :value="10"></el-option>
                <el-option label="现金" :value="20"></el-option>
                <el-option label="支票" :value="30"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="银行账号" prop="bankAccountNumber">
              <el-input v-model="salaryForm.bankAccountNumber" placeholder="请输入银行账号" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onSave">保存</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="employeeSelectorVisible" v-if="employeeSelectorVisible" title="员工基本信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <employee-selector @employee-selected-event="handleEmployeeSelectedEvent">
      </employee-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {defineEmits, defineProps, inject, onMounted, reactive, ref, toRefs} from 'vue';
import salaryApi from '@/api/salaryApi'
import type {FormInstance} from 'element-plus';
import {ElMessage} from 'element-plus'
import type {SalaryForm} from "@/types/req/salaryForm";
import type {Result} from '@/types/result'
import type {Salary} from "@/types/resp/salary";
import type {Id} from "@/types/id";
import { Search } from '@element-plus/icons-vue';
import EmployeeSelector from "@/views/employee/EmployeeSelector.vue";

const props = defineProps<Id>()
const salaryFormRef = ref<FormInstance | null>(null);
const salaryForm = reactive<SalaryForm>({
  employeeId: 0,
  employeeName: '',
  basicSalary: 0,
  performanceSalary: 0,
  bonus: 0,
  allowance: 0,
  overtimePay: 0,
  socialSecurityDeduction: 0,
  housingFundDeduction: 0,
  personalIncomeTaxDeduction: 0,
  otherDeductions: 0,
  grossSalary: 0,
  netSalary: 0,
  payDate: '',
  paymentMethod: undefined,
  bankAccountNumber: '',
})
const employeeSelectorVisible = ref<boolean>(false)
const emit = defineEmits<{
  (e: 'resetSalaryAddEvent'): void;
  (e: 'closeSalaryAddEvent', data?: { search: boolean }): void;
}>()

const rules = reactive({
  employeeName: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' }
  ],
  basicSalary: [
    { required: true, message: '请输入基本工资', trigger: 'blur' }
  ],
  socialSecurityDeduction: [
    { required: true, message: '请输入社保扣除', trigger: 'blur' }
  ],
  housingFundDeduction: [
    { required: true, message: '请输入公积金扣除', trigger: 'blur' }
  ],
  personalIncomeTaxDeduction: [
    { required: true, message: '请输入个人所得税扣除', trigger: 'blur' }
  ],
  otherDeductions: [
    { required: true, message: '请输入其他扣除', trigger: 'blur' }
  ],
  grossSalary: [
    { required: true, message: '请输入应发工资', trigger: 'blur' }
  ],
  netSalary: [
    { required: true, message: '请输入实发工资', trigger: 'blur' }
  ],
  payDate: [
    { required: true, message: '请输入发放日期', trigger: 'blur' }
  ],
});
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')
const formLabelWidth = ref<string>('')

onMounted(() => {
  if (props.id) {
    initSalaryFormById(props.id)
  }
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string, formLabelWidth?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.formLabelWidth) {
    formLabelWidth.value = globalStateRefs.formLabelWidth.value || ''
  }
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
});

const initSalaryFormById = async (id: number) => {
  const resp: Result<Salary> = await salaryApi.findById(id)
  if (resp && resp.code === 1 && resp.data) {
    Object.assign(salaryForm, resp.data)
  }
}

const onReset = () => {
  if (salaryFormRef.value) {
    salaryFormRef.value.resetFields()
  }
  emit('resetSalaryAddEvent')
}

const onSave = () => {
  if (!salaryFormRef.value) {
    return
  }
  salaryFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const resp: Result<void> = await salaryApi.save(salaryForm)
      if (resp && resp.code === 1) {
        ElMessage.success('保存成功')
        emit('closeSalaryAddEvent', {search: true})
      } else {
        ElMessage.error('保存失败:' + (resp.msg ? resp.msg : ''))
      }
    }
  })
}

const findEmployee = () => {
  employeeSelectorVisible.value = true
}

const handleEmployeeSelectedEvent = (selectedEmployee: any) => {
  employeeSelectorVisible.value = false
  if (selectedEmployee && 'employeeId' in selectedEmployee && salaryForm.employeeId !== selectedEmployee['employeeId']) {
    salaryForm.employeeId = selectedEmployee['employeeId']
    salaryForm.employeeName = selectedEmployee['employeeName']
  }
}

const onBack = () => {
  emit('closeSalaryAddEvent')
}
</script>

<style lang="scss">
</style>
